## 弱引用优化测试
## 测试MessageCenter的弱引用机制，验证内存泄漏问题的解决
extends Node

var message_center = preload("res://MessageCenter.gd").new()
var test_results = []


func _ready():
	print("========================================")
	print("开始弱引用优化测试")
	print("========================================\n")
	
	test_weak_reference_cleanup()
	test_manual_unsubscribe()
	test_anonymous_subscription()
	test_object_destroyed_without_unsubscribe()
	
	print_test_summary()


## 测试1：弱引用自动清理
func test_weak_reference_cleanup():
	print("【测试1】弱引用自动清理")
	
	# 创建一个临时对象作为订阅者
	var temp_subscriber = Node.new()
	temp_subscriber.name = "TempSubscriber"
	
	message_center.subscribe(temp_subscriber, "test_channel", func(sender, data):
		print("  回调被触发: ", data)
	)
	
	var count_before = message_center.get_subscription_count("test_channel")
	print("  订阅前数量: ", count_before)
	
	# 发送消息，应该能正常接收
	message_center.send(self, "test_channel", "第一条消息")
	
	# 销毁订阅者对象
	temp_subscriber.queue_free()
	await get_tree().process_frame  # 等待对象真正被释放
	
	# 再次发送消息，弱引用应该自动清理失效的订阅
	message_center.send(self, "test_channel", "第二条消息（不应该被接收）")
	
	var count_after = message_center.get_subscription_count("test_channel")
	print("  清理后数量: ", count_after)
	
	if count_after == 0:
		add_test_result("弱引用自动清理", true, "订阅者销毁后自动清理成功")
	else:
		add_test_result("弱引用自动清理", false, "订阅未被清理，可能存在内存泄漏")
	
	print()


## 测试2：手动取消订阅
func test_manual_unsubscribe():
	print("【测试2】手动取消订阅")
	
	var subscriber = Node.new()
	subscriber.name = "ManualSubscriber"
	
	message_center.subscribe(subscriber, "manual_test", func(sender, data):
		print("  手动订阅回调: ", data)
	)
	
	var count_before = message_center.get_subscription_count("manual_test")
	print("  取消订阅前: ", count_before)
	
	message_center.unsubscribe(subscriber, "manual_test")
	
	var count_after = message_center.get_subscription_count("manual_test")
	print("  取消订阅后: ", count_after)
	
	if count_after == 0:
		add_test_result("手动取消订阅", true, "手动取消订阅成功")
	else:
		add_test_result("手动取消订阅", false, "取消订阅失败")
	
	subscriber.queue_free()
	print()


## 测试3：匿名订阅
func test_anonymous_subscription():
	print("【测试3】匿名订阅")
	
	var anonymous_id = message_center.subscribe_anonymous("anon_channel", func(sender, data):
		print("  匿名订阅回调: ", data)
	)
	
	var count_before = message_center.get_subscription_count("anon_channel")
	print("  匿名订阅数量: ", count_before)
	
	message_center.send(self, "anon_channel", "匿名消息")
	
	# 取消匿名订阅
	message_center.unsubscribe(anonymous_id, "anon_channel")
	
	var count_after = message_center.get_subscription_count("anon_channel")
	print("  取消后数量: ", count_after)
	
	if count_before == 1 and count_after == 0:
		add_test_result("匿名订阅", true, "匿名订阅机制正常")
	else:
		add_test_result("匿名订阅", false, "匿名订阅异常")
	
	print()


## 测试4：对象销毁但未取消订阅（内存泄漏测试）
func test_object_destroyed_without_unsubscribe():
	print("【测试4】对象销毁但未取消订阅（内存泄漏场景）")
	
	var leaked_objects = []
	
	# 创建多个订阅者但不取消订阅
	for i in range(5):
		var temp = Node.new()
		temp.name = "LeakedSubscriber_" + str(i)
		message_center.subscribe(temp, "leak_test", func(sender, data):
			print("  不应该看到此消息: ", data)
		)
		leaked_objects.append(temp)
	
	var count_before = message_center.get_subscription_count("leak_test")
	print("  创建5个订阅者，当前数量: ", count_before)
	
	# 销毁所有订阅者但不调用unsubscribe
	for obj in leaked_objects:
		obj.queue_free()
	
	await get_tree().process_frame
	
	# 发送消息，弱引用应该自动清理所有失效订阅
	message_center.send(self, "leak_test", "清理测试")
	
	var count_after = message_center.get_subscription_count("leak_test")
	print("  对象销毁后，剩余订阅数量: ", count_after)
	
	if count_after == 0:
		add_test_result("内存泄漏防护", true, "弱引用成功防止内存泄漏")
	else:
		add_test_result("内存泄漏防护", false, "仍存在内存泄漏风险")
	
	print()


## 添加测试结果
func add_test_result(test_name: String, passed: bool, message: String):
	test_results.append({
		"name": test_name,
		"passed": passed,
		"message": message
	})


## 打印测试总结
func print_test_summary():
	print("========================================")
	print("测试总结")
	print("========================================")
	
	var passed_count = 0
	var failed_count = 0
	
	for result in test_results:
		var status = "✓ 通过" if result.passed else "✗ 失败"
		var color = "[color=green]" if result.passed else "[color=red]"
		print("%s %s[/color] - %s" % [status, result.name, result.message])
		
		if result.passed:
			passed_count += 1
		else:
			failed_count += 1
	
	print()
	print("总计: %d 个测试，%d 通过，%d 失败" % [test_results.size(), passed_count, failed_count])
	print("========================================")
